package com.example.applearrow.activityresult;

import com.example.applearrow.activityresult.R;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class ActivityB extends Activity {

    // Fields returned in result intent.
    public final static String RESULT = "RESULT";

    // Fields received
    public final static String INPUT_VALUE = "INPUT_VALUE";

    EditText mEditText;
    TextView mTextViewInputValues;

    private String mAction;
    private Uri mDataUri;
    private String mInput;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_b);

        mEditText = (EditText) findViewById(R.id.editTextReturn);
        mTextViewInputValues = (TextView) findViewById(R.id.inputValues);
    }

    @Override
    protected void onResume() {
        super.onResume();
        retrieveInputParams();
    }

    private void retrieveInputParams() {
        mAction = getIntent().getAction();
        mDataUri = getIntent().getData();
        mInput = getIntent().getStringExtra(INPUT_VALUE);
        updateInputParamsOnUI();
    }

    private void updateInputParamsOnUI() {

        StringBuilder sb = new StringBuilder();
        // action
        if (mAction != null && !mAction.equals("")) {
            sb.append(getString(R.string.action));
            sb.append("=");
            sb.append(mAction);
            sb.append("\n");
        }
        // data uri
        if (mDataUri != null) {
            sb.append(getString(R.string.data_uri));
            sb.append("=");
            sb.append(mDataUri.toString());
            sb.append("\n");
        }
        // INPUT_VALUE
        sb.append(INPUT_VALUE);
        sb.append("=");
        sb.append(mInput);
        sb.append("\n");
        
        mTextViewInputValues.setText(sb.toString());
    }

    public void onReturnOkButtonClick(View v) {
        Intent returnIntent = new Intent();
        final String result = mEditText.getText().toString();
        if (!result.equals("")) {
            returnIntent.putExtra(RESULT, result);
        }
        setResult(RESULT_OK, returnIntent);
        finish();
    }

    public void onReturnCancelButtonClick(View v) {
        Intent returnIntent = new Intent();
        setResult(RESULT_CANCELED, returnIntent);
        finish();
    }

}
